import React, { useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';
import cookie from 'react-cookies';
import { getHashQuery } from '@/utils';
import { PageProps } from '@/typings/react.type';

// 校验当前用户登录状态
const PrivateRoute = ({ component: Component, meta, title, ...rest }) => {
  const isPrivate = cookie.load(`demokey`, true) || false;

  useEffect(() => {
    const checkPass = async () => {
      if (!isPrivate) {
        // window.location.href = CORGI_LOGIN_URL;
      }
    };
    checkPass();
  }, [isPrivate]);

  return (
    <Route
      {...rest}
      render={(props: PageProps) => {
        if (title) document.title = title; // 设置页面标题

        /**
         * 在页面组件的props注入hash后面的query参数。
         *
         * 例子：http://localhost/bxcAibaoClient/#/my?status=trial
         * 组件内可通过 this.props.location.query 获取
         */
        props.location.query = {
          ...props.location.query,
          ...getHashQuery(),
        };
        // props.match.query = getHashQuery();

        // 校验是否需要登录
        return !meta.needLogin || isPrivate ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/' }} />
        );
      }}
    />
  );
};

export default PrivateRoute;
